﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using ESOL.Common;
using ESOL.Business.Bpt;
using ESOL.Common.Entity;
using ESOL.Business.Mst;
using System.IO;

namespace ESOL.WinUI.Bpt
{
    public partial class frmMaintainTaskImport : BaseForm.frmBaseDialogyMaintainForm
    {
        #region Variable
        public string SelectTaskCode { get; set; }
        public string SelectAppCode { get; set; }
        public string SelectAppPerson { get; set; }
        string sDeflePictureFile = CommonParameter.DeflePictureFile;
        #endregion

        #region Constructor
        public frmMaintainTaskImport()
        {
            InitializeComponent();
        }
        #endregion

        #region Functions
        private void InitGridDataConstruction()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("件号");
            dt.Columns.Add("图号或标准号");
            dt.Columns.Add("名称");
            dt.Columns.Add("数量");
            dt.Columns.Add("材料");
            dt.Columns.Add("备注");
            dt.Columns.Add("图片路径");
            gvMain.DataSource = dt;
            DataTable dt2 = dt.Clone();
            gvMain2.DataSource = dt2;
        }

        /// <summary>
        /// 读取CAD文件
        /// </summary>
        /// <param name="sFilePath"></param>
        private void ImpCADFile(string sFilePath)
        {
            if (sFilePath.Equals(""))
            {
                return;
            }
            try
            {
                Cursor = Cursors.WaitCursor;
                DataTable dtnew = DwgFile.ReadDwg(sFilePath);
                Cursor = Cursors.Default;
                DataTable dtRead = new DataTable();
                dtRead = dtnew.Copy();
                for (int cl = 0; cl < dtnew.Columns.Count; cl++)
                {
                    if (string.IsNullOrEmpty(dtnew.Rows[dtRead.Rows.Count - 1][cl].ToString()))
                    {
                        string cName = "";
                        cName = dtnew.Columns[cl].ColumnName;
                        dtRead.Columns.Remove(cName);
                    }
                }
                DataTable dt = gvMain.DataSource as DataTable;
                for (int k = 0; k < dtRead.Rows.Count - 1; k++)
                {
                    dt.Rows.Add();
                }

                for (int k = 0; k < dtRead.Rows.Count - 1; k++)
                {
                    if (dtRead.Rows[k][0] == null)
                    {
                        continue;
                    }
                    int nRow = 0;
                    try
                    {
                        nRow = int.Parse(dtRead.Rows[k][0].ToString());
                    }
                    catch (Exception ex)
                    {
                        continue;
                    }
                    dt.Rows[nRow]["件号"] = dtRead.Rows[k][0].ToString();
                    if (string.IsNullOrEmpty(dtRead.Rows[k][4].ToString()))
                    {
                        dt.Rows[nRow]["图号或标准号"] = "";
                    }
                    else
                    {
                        dt.Rows[nRow]["图号或标准号"] = dtRead.Rows[k][4].ToString().Substring(0, 15);
                    }
                    dt.Rows[nRow]["名称"] = dtRead.Rows[k][1].ToString();
                    dt.Rows[nRow]["数量"] = dtRead.Rows[k][2].ToString();
                    dt.Rows[nRow]["材料"] = dtRead.Rows[k][3].ToString();
                    dt.Rows[nRow]["备注"] = dtRead.Rows[k][5].ToString();
                }
                gvMain.DataSource = dt;
                btnPictureFilePath.Enabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("CAD图纸加载失败，明细为： " + ex.Message);
            }

        }

        private void SetFiled(string sTaskCode)
        {
            string condition = " AND a.TASK_CODE LIKE '%" + sTaskCode + "%'";
            string rowCount = "100";
            string orderBy = "TASK_CODE";
            DataTable dt = BptDrawBlueprintBs.GetCustomerByCondition(condition, orderBy, rowCount);
            if (dt.Rows.Count > 0)
            {
                txtAppCode.Text = dt.Rows[0]["APPLICATION_CODE"].ToString();
                txtTaskCode.Text = sTaskCode;
                txtAppPerson.Text = dt.Rows[0]["NAME_CN"].ToString();
                txtAppCode2.Text = dt.Rows[0]["APPLICATION_CODE"].ToString();
                txtTaskCode2.Text = sTaskCode;
                txtAppPerson2.Text = dt.Rows[0]["NAME_CN"].ToString();
            }
        }

        private byte[] FileToByte(string pStrFName)
        {
            FileInfo fi = new FileInfo(pStrFName);
            FileStream fs = fi.OpenRead();
            byte[] bytes = new byte[fs.Length];
            fs.Read(bytes, 0, Convert.ToInt32(fs.Length));
            return bytes;
        }

        private void ImpXlsFile(string sFilePath)
        {
            if (sFilePath.Equals(""))
            {
                return;
            }
            try
            {
                Cursor = Cursors.WaitCursor;
                DataTable dtnew = DwgFile.Readxls(sFilePath);
                Cursor = Cursors.Default;
                gvMain.DataSource = dtnew;
                btnPictureFilePath.Enabled = true;

            }
            catch (Exception ex)
            {
                MessageBox.Show("Excel文件加载失败!" + ex.Message);
            }
        }

        private void AddLineFile(DataRow drSelected)
        {
            string sFilePath = "";
            OpenFileDialog op = new OpenFileDialog();
            op.Title = "图片图纸文件选择";
            op.FileName = "";
            op.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyComputer);
            op.Filter = "图片文件(*.jpg,*.pdf)|*.jpg;*.pdf";
            op.ValidateNames = true;
            op.CheckFileExists = true;
            op.CheckPathExists = true;

            if (op.ShowDialog() == DialogResult.OK)
            {
                sFilePath = op.FileName;
                string sItemCode = "";
                sItemCode = sFilePath.Substring(sFilePath.LastIndexOf(@"\") + 1);
                for (int i = sFilePath.Length - 1; i >= 0; i--)
                {
                    if (sFilePath.Substring(i, 1) == @"\")
                    {
                        sItemCode = sFilePath.Substring(i + 1, sFilePath.Length - i - 1);
                        break;
                    }
                }
                if (sItemCode == drSelected["图号或标准号"].ToString() + ".jpg")
                {
                    drSelected["图片路径"] = sFilePath;
                }
                else
                {
                    MessageBox.Show("不是对应的图纸图片！");
                    return;
                }
            }
        }

        private void SaveMultiple()
        {
            Cursor = Cursors.WaitCursor;

            DataTable dt_Soure = new DataTable();
            dt_Soure = (DataTable)gvMain.DataSource;
            DataTable dt = dt_Soure.Clone();
            for (int i = 0; i < dt_Soure.Rows.Count; i++)
            {
                if (string.IsNullOrEmpty(dt_Soure.Rows[i][0].ToString()) == false)
                {
                    dt.ImportRow(dt_Soure.Rows[i]);
                }
            }

            if (BptBlueprintBs.SavePrint_New(dt, SelectTaskCode))
            {
                EsolWevServices.EsolService EService = new EsolWevServices.EsolService();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string sFilester = dt.Rows[i][6].ToString();
                    if (System.IO.File.Exists(sFilester))
                    {
                        string FileName = sFilester.Substring(sFilester.LastIndexOf("\\") + 1);
                        try
                        {
                            ///处理上载的文件流信息。 
                            byte[] b = FileToByte(sFilester);
                            ///调用Web   Services的UploadFile方法进行上载文件。
                            string aaa = EService.UploadFile(b, FileName);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("数据保存成功，但图纸上传出错了！原因为： " + ex.Message);
                            EService.Dispose();
                            this.Close();
                        }

                    }
                }
                //EService.Dispose();
                MessageBox.Show("图纸导入完成！");
                Cursor = Cursors.Default;
                this.DialogResult = DialogResult.OK;
            }
            Cursor = Cursors.Default;
        }

        private void SaveSimple()
        {
            if (gvMain2.DataSource == null)
            {
                MessageBox.Show("导入明细不可为空！","Information",MessageBoxButtons.OK,MessageBoxIcon.Information);
            }
            DataTable dt = gvMain2.DataSource as DataTable;
            
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                for (int k = 0; k < dt.Columns.Count; k++)
                {
                    if (string.IsNullOrEmpty(dt.Rows[i][k].ToString()))
                    {
                        MessageBox.Show("第 " + (i + 1) + " 行， '" + gridView2.Columns[k].Caption + "' 列，不能为空！", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                }
            }
            if (!MstProductBs.GetProductByCode(dt.Rows[0]["图号或标准号"].ToString()))
            {
                MessageBox.Show("物料编码不存在，请先创建编码！", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (BptBlueprintBs.SavePrint(dt, SelectTaskCode))
            {
                //EsolWevServices.EsolService EService = new EsolWevServices.EsolService();
                EsolWevServices.EsolService EService = new EsolWevServices.EsolService();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string sFilester = dt.Rows[i][6].ToString();
                    if (System.IO.File.Exists(sFilester))
                    {
                        string FileName = sFilester.Substring(sFilester.LastIndexOf("\\") + 1);
                        try
                        {
                            ///处理上载的文件流信息。 
                            byte[] b = FileToByte(sFilester);
                            ///调用Web   Services的UploadFile方法进行上载文件。
                            string aaa = EService.UploadFile(b, FileName);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("数据保存成功，但图纸上传出错了！原因为： " + ex.Message);
                            EService.Dispose();
                            this.Close();
                        }

                    }
                }
                //EService.Dispose();
                MessageBox.Show("图纸导入完成！");
                this.DialogResult = DialogResult.OK;
            }
        }

        private void EditCode(DataRow dr)
        {
            if (!string.IsNullOrEmpty(dr[1].ToString()))
            {
                MessageBox.Show("该列已经有编码了!");
                return;
            }
            frmMaintainEncoder frm = new frmMaintainEncoder();
            frm.ThisActionType = ActionType.New;
            if (frm.ShowDialog() == DialogResult.OK)
            {
                MstProductEntity ProductEntity = frm.SelectedProduct;
                dr[1] = ProductEntity.ProductCode;
            }
        }
        #endregion

        #region Event
        protected override void OnShown(EventArgs e)
        {
            btnPictureFilePath.Enabled = false;
            if (SelectTaskCode.Equals(""))
            {
                this.Close();
            }
            SetFiled(SelectTaskCode);
            InitGridDataConstruction();
            DataTable dt = gvMain.DataSource as DataTable;
            DataRow dr = dt.NewRow();
            dt.Rows.Add(dr);
            base.OnShown(e);
        }

        DataRow drSelected1;
        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            drSelected1 = gridView1.GetDataRow(e.FocusedRowHandle);
        }

        DataRow drSelected2;
        private void gridView2_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            drSelected2 = gridView2.GetDataRow(e.FocusedRowHandle);
        }

        private void btnCloose_Click(object sender, EventArgs e)
        {
            string sFilePath = "";
            OpenFileDialog op = new OpenFileDialog();
            op.Title = "CAD图纸文件选择";
            op.FileName = "";
            op.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyComputer);
            op.Filter = "CAD文件(*.dwg)|*.dwg";
            op.ValidateNames = true;
            op.CheckFileExists = true;
            op.CheckPathExists = true;
            try
            {
                if (op.ShowDialog() == DialogResult.OK)
                {
                    sFilePath = op.FileName;
                    txtFilePath.Text = sFilePath;
                    ImpCADFile(sFilePath);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("CAD图纸加载失败，明细为： " + ex.Message);
            }
        }

        private void btnImportXls_Click(object sender, EventArgs e)
        {
            string sFilePath = "";
            OpenFileDialog op = new OpenFileDialog();
            op.Title = "EXCEL文件选择";
            op.FileName = "";
            op.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyComputer);
            op.Filter = "EXCEL文件(*.xls,*.xlsx)|*.xls;*.xlsx";

            op.ValidateNames = true;
            op.CheckFileExists = true;
            op.CheckPathExists = true;
            try
            {
                if (op.ShowDialog() == DialogResult.OK)
                {
                    sFilePath = op.FileName;
                    txtFilePath.Text = sFilePath;
                    ImpXlsFile(sFilePath);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("CAD图纸加载失败，明细为： " + ex.Message);
            }
        }

        private void btnPictureFilePath_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
            folderBrowserDialog1.Description = "请选择导入图片的文件夹";
            folderBrowserDialog1.ShowNewFolderButton = true;
            folderBrowserDialog1.RootFolder = Environment.SpecialFolder.MyComputer;
            DialogResult result = folderBrowserDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                string folderName = folderBrowserDialog1.SelectedPath;
                if (folderName != "")
                {
                    txtPictureFilePath.Text = folderName;
                    DataTable dt = new DataTable();
                    dt = (DataTable)gvMain.DataSource;
                    if (dt.Rows.Count > 0)
                    {
                        for (int j = 0; j < dt.Rows.Count; j++)
                        {
                            string ItemPicture = folderName + @"\" + dt.Rows[j]["图号或标准号"].ToString() + ".jpg";
                            if (File.Exists(ItemPicture))
                            {
                                dt.Rows[j]["图片路径"] = ItemPicture;
                            }
                            else
                            {
                                dt.Rows[j]["图片路径"] = "未找到图片";
                            }
                        }
                    }
                }
            }
        }

        private void btnOnePicture_Click(object sender, EventArgs e)
        {
            string sFilePath = "";
            OpenFileDialog op = new OpenFileDialog();
            op.Title = "图片图纸文件选择";
            op.FileName = "";
            op.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyComputer);
            op.Filter = "图片文件(*.jpg,*.pdf)|*.jpg;*.pdf";
            op.ValidateNames = true;
            op.CheckFileExists = true;
            op.CheckPathExists = true;

            if (op.ShowDialog() == DialogResult.OK)
            {
                sFilePath = op.FileName;
                txtOnePicture.Text = sFilePath;
                //EsolWevServices.EsolService EService = new EsolWevServices.EsolService();
                EsolWevServices.EsolService EService = new EsolWevServices.EsolService();
                string FileName = sFilePath.Substring(sFilePath.LastIndexOf("\\") + 1);
                try
                {
                    ///处理上载的文件流信息。 
                    byte[] b = FileToByte(sFilePath);
                    ///调用Web   Services的UploadFile方法进行上载文件。
                    string aaa = EService.UploadFile(b, FileName);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("图纸上传出错了！原因为： " + ex.Message);
                }

            }
        }

        private void colFilePath1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            AddLineFile(drSelected1);
        }

        private void colFilePath2_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            AddLineFile(drSelected2);
        }

        protected override void Click_Save()
        {
            if (devTabControl1.SelectedTabPageIndex == 0)
            {
                SaveMultiple();
            }
            else
            {
                SaveSimple();
            }
        }

        private void colCodeEditer2_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            EditCode(drSelected2);
        }

        private void colCodeEditer1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            EditCode(drSelected1);
        }

        #endregion
    }
}
